import React, {useEffect, useRef, useState} from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import InputBase from '@material-ui/core/InputBase';
import {alpha, makeStyles, useTheme} from '@material-ui/core/styles';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import {useHistory} from 'react-router-dom'
import Drawer from "@material-ui/core/Drawer";

import Divider from "@material-ui/core/Divider";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import ChevronRightIcon from "@material-ui/icons/ChevronRight";
import clsx from "clsx";
import Box from "@material-ui/core/Box";
import Sidenav from "./Sidenav";

const drawerWidth = 240;
const SMdrawerWidth = 180;

const useStyles = makeStyles((theme) => ({
    root: {
        flexGrow: 1,
        maxWidth: 1300,
        margin: "auto",
    },
    menuButton: {
        marginRight: theme.spacing(2),
    },
    title: {
        flexGrow: 1,
        display: 'none',
        '&:hover': {
            cursor: "pointer",
        },
        fontStyle: "italic",
        [theme.breakpoints.up('sm')]: {
            display: 'block',
        },
    },
    search: {
        position: 'relative',
        borderRadius: theme.shape.borderRadius,
        backgroundColor: alpha(theme.palette.common.white, 0.15),
        '&:hover': {
            backgroundColor: alpha(theme.palette.common.white, 0.25),
        },
        marginLeft: 0,
        width: '100%',
        [theme.breakpoints.up('sm')]: {
            marginLeft: theme.spacing(1),
            width: 'auto',
        },
    },
    searchIcon: {
        padding: theme.spacing(0, 2),
        height: '100%',
        position: 'absolute',
        pointerEvents: 'none',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    inputRoot: {
        color: 'inherit',
    },
    inputInput: {
        padding: theme.spacing(1, 1, 1, 0),
        // vertical padding + font size from searchIcon
        paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
        transition: theme.transitions.create('width'),
        width: '100%',
        // [theme.breakpoints.up('sm')]: {
        //     width: '12ch',
        //     '&:focus': {
        //         width: '20ch',
        //     },
        // },
    },

    drawer: {
        width: drawerWidth,
        flexShrink: 0,
        [theme.breakpoints.down('sm')]: {
            width: SMdrawerWidth,
            paddingLeft: theme.spacing(4)
        }
    },
    drawerPaper: {
        width: drawerWidth,
        [theme.breakpoints.down('sm')]: {
            width: SMdrawerWidth,
            paddingLeft: theme.spacing(4)
        }
    },
    drawerHeader: {
        display: 'flex',
        alignItems: 'center',
        padding: theme.spacing(0, 1),
        // necessary for content to be below app bar
        // ...theme.mixins.toolbar,
        justifyContent: 'flex-end',
    },
    hide: {
        //手机屏才显示抽屉
        [theme.breakpoints.up('sm')]: {
            display: "none",
        }
    },
    backToHome: {
        fontWeight: "800",
        marginLeft: theme.spacing(1),
        color: theme.palette.secondary.dark,
    },
    iconButton: {
        padding: 10,
    },
}));


export default function Navbar() {
    const classes = useStyles()
    const history = useHistory()
    const [keyword, setKeyword] = useState('')
    const [open, setOpen] = React.useState(false);
    const theme = useTheme();
    const drawerRef = useRef(null)

    const handleDrawerOpen = () => {
        setOpen(true);
    };

    const handleDrawerClose = () => {
        setOpen(false);
    };
    const handleSubmit = e => {
        e.preventDefault();
        if (keyword.length > 0) {
            history.push(`/search/?keyword=${keyword}`)
        }
    }
    useEffect(() => {
        function handleClickOutSideNav(event) {
            if (open && drawerRef.current && !drawerRef.current.contains(event.target))
                // console.log('You click somewhere');
                setOpen(false)
        }
        document.addEventListener('mousedown', handleClickOutSideNav)

        return () => document.removeEventListener('mousedown', handleClickOutSideNav)
    }, [open, drawerRef])


    return (
        <div className={classes.root}>
            <AppBar position="static" elevation={0}>
                <Toolbar id="back-to-top-anchor">
                    <IconButton
                        edge="start"
                        className={clsx(classes.menuButton, classes.hide)}
                        color="inherit"
                        aria-label="open drawer"
                        onClick={handleDrawerOpen}
                    >
                        <MenuIcon/>

                    </IconButton>
                    <Typography
                        className={classes.title}
                        variant="h6"
                        noWrap
                        onClick={() => history.push('/')}
                    >
                        YZTBOOKS <Typography variant="caption">  在线电子书阅读</Typography>
                    </Typography>

                    <div className={classes.search}>
                        <form onSubmit={handleSubmit}>
                            <div className={classes.searchIcon}>
                                <SearchIcon/>
                            </div>
                            <InputBase
                                placeholder="查找图书"
                                classes={{
                                    root: classes.inputRoot,
                                    input: classes.inputInput,
                                }}
                                inputProps={{'aria-label': 'search'}}
                                value={keyword}
                                onChange={e => setKeyword(e.target.value)}
                            />
                        </form>
                    </div>

                </Toolbar>
            </AppBar>

            <Drawer
                ref={drawerRef}
                className={clsx(classes.drawer, classes.hide)}
                variant="persistent"
                anchor="left"
                open={open}
                classes={{
                    paper: classes.drawerPaper,
                }}
            >
                <div className={classes.drawerHeader}>
                    <Box variant="h6" flexGrow={1} onClick={() => history.push('/')}
                         className={classes.backToHome}>返回首页</Box>
                    <IconButton onClick={handleDrawerClose}>
                        {theme.direction === 'ltr' ? <ChevronLeftIcon/> : <ChevronRightIcon/>}
                    </IconButton>
                </div>

                <Divider/>
                <Sidenav/>
            </Drawer>
        </div>
    );
}